package com.xie.smfs.entity;

import com.xie.smfs.item.RedGhostCandleItem;
import com.xie.smfs.util.PlayerBlockActionTracker;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.damage.DamageType;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.util.Identifier;
import net.minecraft.world.World;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class BlockGhostEntity extends GhostEntity {

    private static final Map<UUID, Boolean> playerInteractingWithBlocks = new HashMap<>();


    public BlockGhostEntity(EntityType<? extends GhostEntity> entityType, World world) {
        super(entityType, world, true, 3, 20.0); // 启用鬼域，等级3，半径20
        this.ghostLevel = 2; // 设置危险等级B
    }

    @Override
    protected boolean shouldAttackPlayer(PlayerEntity player) {
        if (isSuppressed() || isDeadlocked() || RedGhostCandleItem.isHoldingCandle(player)) {
            playerInteractingWithBlocks.put(player.getUuid(), false);
            return false;
        }

        boolean isInteractingWithBlocks = isPlayerInteractingWithBlocks(player);
        playerInteractingWithBlocks.put(player.getUuid(), isInteractingWithBlocks);
        return isInteractingWithBlocks;
    }

    private boolean isPlayerInteractingWithBlocks(PlayerEntity player) {
        // 检测玩家是否有方块操作记录
        return PlayerBlockActionTracker.hasRecentBlockAction(player.getUuid(), 20); // 20刻内有方块操作
    }

    @Override
    public void tick() {
        super.tick();

        if (this.getVisible()) {
            this.setVisibleTicks(this.getVisibleTicks() + 1);
            // 3秒后隐藏
            if (this.getVisibleTicks() >= 60) {
                this.setVisible(false);
                this.setInvisible(true);
            }
        } else {
            this.setInvisible(true);
        }
    }

    @Override
    protected void executeAttack(PlayerEntity player) {
        // 触发攻击时显示实体
        this.setVisible(true);
        this.setVisibleTicks(0);
        this.setInvisible(false);
        // 瞬移到玩家面前
        this.teleport(player.getX(), player.getY(), player.getZ());
        // 应用伤害和效果
        RegistryEntry<DamageType> mobDamageType = this.getWorld().getRegistryManager().get(RegistryKeys.DAMAGE_TYPE)
            .getEntry(RegistryKey.of(RegistryKeys.DAMAGE_TYPE, new Identifier("smfs", "ghost")))
            .orElseThrow(() -> new IllegalStateException("MOB_ATTACK damage type not found"));
        DamageSource damageSource = new DamageSource(mobDamageType, this);
        player.damage(damageSource, 80.0f); // 造成80点伤害
    }
}